package com.htudata.transctNode.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.htudata.alarm.pojo.po.AlarmLevelPO;
import com.htudata.alarm.service.AlarmLevelService;
import com.htudata.transctNode.dao.TransctLinkDao;
import com.htudata.transctNode.service.TransctLinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class TransctLinkServiceImpl implements TransctLinkService {

  @Autowired
  private AlarmLevelService alarmLevelService;
  
  @Autowired
  TransctLinkDao linkDao;
  
  public int copyLinkToLinkTemp(String flowId) {
    return this.linkDao.insertLinkToLinkTemp(flowId);
  }
  
  public int deleteTempLinksByFlowId(String flowId) {
    return this.linkDao.deleteTempLinksByFlowId(flowId);
  }
  
  public Map<String, JSONObject> getLinkAlarmsByFlowId(String flowId) {
    JSONArray linkAlarms = this.linkDao.selectLinkAlarmsByFlowId(flowId);
    return distinctLinkAlarms(linkAlarms);
  }
  
  public Map<String, JSONObject> distinctLinkAlarms(JSONArray linkAlarms) {
    Map<String, JSONObject> linkAlarmMap = new HashMap<>();
    List<AlarmLevelPO> alarmLevelList = this.alarmLevelService.getAlarmLevelList(null);
    if (!Objects.isNull(linkAlarms) && linkAlarms.size() > 0)
      linkAlarms.forEach(linkAlarm -> {
            JSONObject linkAlarmObject = (JSONObject)linkAlarm;
            if (!linkAlarmMap.containsKey(linkAlarmObject.getString("linkId"))) {
              AlarmLevelPO alarmLevelPO = AlarmLevelService.getAlarmLevelInfo(alarmLevelList, linkAlarmObject.getInteger("level").intValue());
              linkAlarmObject.put("color", alarmLevelPO.getColor());
              linkAlarmMap.put(linkAlarmObject.getString("linkId"), linkAlarmObject);
            } else {
              JSONObject linkAlarmObject1 = linkAlarmMap.get(linkAlarmObject.getString("linkId"));
              int level1 = linkAlarmObject1.getInteger("level").intValue();
              int level = linkAlarmObject.getInteger("level").intValue();
              if (level1 < level) {
                AlarmLevelPO alarmLevelPO = AlarmLevelService.getAlarmLevelInfo(alarmLevelList, linkAlarmObject.getInteger("level").intValue());
                linkAlarmObject.put("color", alarmLevelPO.getColor());
                linkAlarmMap.put(linkAlarmObject.getString("linkId"), linkAlarmObject);
              } 
            } 
          }); 
    return linkAlarmMap;
  }
}
